package com.sufen.seckill.config;

import com.sufen.seckill.exception.GlobalException;
import com.sufen.seckill.pojo.User;
import com.sufen.seckill.service.IUserService;
import com.sufen.seckill.utils.CookieUtil;
import com.sufen.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author sufen
 * @Date 2021/10/20 12:32
 * @Version 1.0
 * 功能描述：放到WebConfig里面的
 */
@Component
@Slf4j
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz=parameter.getParameterType();
        return clazz== User.class;
    }

    @Autowired
    private IUserService userService;

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request=webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response=webRequest.getNativeResponse(HttpServletResponse.class);
        //取Cookie
        String ticket= CookieUtil.getCookieValue(request,"userTicket");
        log.info("Controller的前置校验器UserArgumentResolver对传进每个Controller的Cookie进行判断，Cookie(即userTicket)的值为："+ticket);
        if(StringUtils.isEmpty(ticket)){
            throw new GlobalException(RespBeanEnum.Cookie_NULL_ERROR);
//            return null;
        }
        User user=userService.getUserByCookie(ticket,request,response);
        if(user==null){
            log.info("传进来了Cookie,但是Cookie是错的，从redis里面取不到user");
            throw new GlobalException(RespBeanEnum.User_NULL_ERROR);
//            return user;
        }
        log.info("Controller的前置校验器UserArgumentResolver对传进每个Controller的Cookie向redis里校验成功，成功取出redis里的user");
        return user;
    }
}
